package cn.xd.core.ddd.manager;

import cn.xd.core.ddd.db.DbContext;
import cn.xd.core.ddd.diff.EntityDiff;
import cn.xd.core.ddd.entity.Entity;
import cn.xd.core.ddd.value.IdValue;

/**
 * @author : mirzaLin
 * @data : 2023/11/19
 * @description :
 **/
public class ThreadLocalAggregateManager<T extends Entity<ID>, ID extends IdValue> implements AggregateManager<T, ID> {

    private final ThreadLocal<DbContext<T, ID>> context;
//    private Class<T> targetClass;

    public ThreadLocalAggregateManager(Class<T> targetClass) {
//        this.targetClass = targetClass;
        this.context = ThreadLocal.withInitial(() -> new DbContext<>(targetClass));
    }

    @Override
    public void attach(T aggregate) {
        context.get().attach(aggregate);
    }

    @Override
    public void attach(T aggregate, ID id) {
//        context.get().setId(aggregate, id);
        context.get().attach(aggregate);
    }

    @Override
    public void detach(T aggregate) {
        context.get().detach(aggregate);
    }

    @Override
    public void detachById(ID id) {
        context.get().detach(id);
    }

    @Override
    public T find(IdValue id) {
        return context.get().find(id);
    }

    @Override
    public EntityDiff detectChanges(T aggregate) {
        return context.get().detectChanges(aggregate);
    }

    @Override
    public void merge(T aggregate) {
        context.get().merge(aggregate);
    }
}
